# -*- coding: utf-8 -*-
from utils.config import *
from utils.utils import *
import pandas as pd
import utils.MyTT as Mytt
# import logging
from utils.log import Loggers
from utils.pushService import PushService
import numpy as np

# 每小时的前5分钟 不调用脚本，防止数据不完整
should_skip()
logger = Loggers('junxianGMMA')
# logger.clear()

pushSer = PushService('顾比趋势策略')

# 计算所有的均线组
def calculate_gmma(df, short_spans=[3, 5, 8, 10, 12, 15], long_spans=[30, 35, 40, 45, 50, 60]):
    """计算GMMA的短期和长期均线组"""
    for span in short_spans:
        df[f'EMA_short_{span}'] = df['close'].ewm(span=span, adjust=False).mean()
    for span in long_spans:
        df[f'EMA_long_{span}'] = df['close'].ewm(span=span, adjust=False).mean()
    return df

def detect_trend(df):
    # 计算短期组和长期组的平均值（简化判断）
    df['short_avg'] = df[[f'EMA_short_{p}' for p in [3,5,8,10,12,15]]].mean(axis=1)
    df['long_avg'] = df[[f'EMA_long_{p}' for p in [30,35,40,45,50,60]]].mean(axis=1)
    
    # 判断趋势（1=多头，-1=空头）
    df['trend'] = np.where(df['short_avg'] > df['long_avg'], 1, -1)
    
    # 标记趋势变化点（避免频繁变动）
    df['signal'] = df['trend'].diff().ne(0).astype(int) * df['trend']
    
    return df
    
firstOne = 0
# 循环处理
for instId in config_movingAverage_instId:
    # 读取300条最新的数据
    try:
        df = loadCsvData(instId,'1d',300)
    except:
        continue
    # 计算顾比线
    df = calculate_gmma(df)

    # 计算趋势
    df = detect_trend(df)

    # # 寻找开单信号
    # df['signal'] = 0 
    # # 做多信号  大级别多头趋势，收盘价>10均线 ，最高价不超过布林带上轨
    # df.loc[(df['close'] > df['ema10']) & (df['cross_body'] == 0) & (df['upper_shadow']>df['body'] *2)  ,'signal'] = 1
    # df.loc[(df['close'] < df['ema10']) & (df['cross_body'] == 0) & (df['lower_shadow']>df['body'] *2)  ,'signal'] = -1
    
    # 快速计算信号近期胜率
    # shenglv5,shenglv10 = getShenglv(df)
    # 取出所有满足条件的信号数据
    df_signal = df[df['signal']!=0]
    # 拿到最后出现信号的数据
    after_signal = df_signal.iloc[-1]
    after_signal2 = df_signal.iloc[-2]

    xiaoshu = 1 if after_signal['close']>0 else 3
    # 计算止损点位
    # zhisun= round(after_signal['recent_low'] + (after_signal['atr'] if after_signal['signal'] == -1 else after_signal['atr']*-1),xiaoshu)

    fangxiang = '做多' if after_signal['signal']>0 else '做空'
    signal_text = f"{instId}{fangxiang} 最近信号：{after_signal.name} 收盘价：{after_signal['close']} "

    fangxiang2 = '做多' if after_signal2['signal']>0 else '做空'
    diezhang = round(( after_signal['close'] - after_signal2['close']) / after_signal2['close'] * 100,2)
    signal_text2 = f"上次信号：{after_signal2.name}({fangxiang2}) 距今跌涨：{diezhang}%"

    # # 计算止损位置
    # zhisunR = round( abs((zhisun - after_signal['close'])) /after_signal['close'] *100,2)

    # signal_text+= f"止损：{zhisun}({zhisunR}%)"
    hour = getHoursPassed(after_signal.name)
    # 进行日志记录
    if hour < 25:
        if firstOne == 0:
            firstOne=1
            extent = [
                 signal_text2,
            f"可采用固定止损：2%，\n\n",
            "温馨提示：\n\n",
            "策略属于趋势策略，观察顾比长期组均线，当处于粘合状态时，属于震荡行情，不可贪多。注意控制回撤\n\n",
        ]
        else:
            extent = [
                 signal_text2,
        ]
        # 25小时内的新信号 就可以 进行钉钉推送
        if pushSer.add_push_item(after_signal, instId,extent):
            logger.info(signal_text)

    # 完成消息的通知
pushSer.push_message()

